﻿var JskitFileUpload = function (rHd) {
    var __hd = (typeof (rHd) == "string") ? rHd : "jskitFileUpload";
    var __file = null;
    var __key = jskitUtil.guid();
    var __isFormReady = false;
    var __action = "Ws/_Upload.aspx";
    var __convas = null;
    var __listData = null;
    var __listBox = null;
    var __listRequest = "Ws/_FileAction.aspx?act=list&model=?&model_key=?";
    var __form = null;
    var __sending = false;
    var __viewUrl = "";
    var __msgObj = null;
    var __modelKey = "undefined";
    var __model = "undefined";
    var __title = unescape("%u4E0A%u4F20%u6587%u4EF6%u7BA1%u7406");

    //BEGIN:options
    var __showDetails = false;
    var __filePattern = null;
    //END--

    //构造面板    
    var __buildWindow = function () {
        if (__convas == null) {
            __convas = document.createElement("div");
            $("body").appendChild(__convas);
        }
        var _str = new Array();
        _str.push('<form target="file_upload_frame" id="fm_' + __key + '" action="' + __action + '" method="post" enctype="multipart/form-data" >');
        //for debug
        //_str.push('<form target="_blank" id="fm_'+__key+'" action="'+__action+'" method="post" enctype="multipart/form-data" >');
        _str.push('<div class="fileupload_border_shadow"></div>');
        _str.push('<div class="fileupload_title_bar">' + __title + '</div>');
        _str.push('<div class="fileupload_list" id="l_' + __key + '"></div>');
        _str.push('<div class="fileupload_bar">');
        _str.push('<div class="fileupload_bar1" id="m_' + __key + '">&nbsp;</div>');
        _str.push('<div class="fileupload_bar3">');
        _str.push('<input class="fileupload_btn" type="button" value="' + unescape("%u524D%u7F6E") + '" onclick="' + __hd + '.doTop(this,event)" />');
        _str.push('<input class="fileupload_btn" type="button" value="' + unescape("%u5220%u9664") + '" onclick="' + __hd + '.doDelete(this,event)" />');
        _str.push('<input class="fileupload_btn" type="button" value="' + unescape("%u5173%u95ED") + '" onclick="' + __hd + '.close()" />');
        _str.push('</div>');
        _str.push('<div class="fileupload_bar2">');
        _str.push('<input type="file" name="file_upload" class="fileupload_file" id="f_' + __key + '" onchange="' + __hd + '.doUpload(this,event)" hidefoucs="true" />');
        _str.push('<div class="fileupload_add_btn">&nbsp;<div>');
        _str.push('</div>');
        _str.push('</div>');
        _str.push('<input type="hidden" name="failed_handler" value="' + __hd + '.failed" />');
        _str.push('<input type="hidden" name="succeed_handler" value="' + __hd + '.succeed" />');
        _str.push('<input type="hidden" name="model_name" value="' + __model + '" />');
        _str.push('<input type="hidden" name="model_key" value="' + __modelKey + '" />');
        _str.push('<iframe name="file_upload_frame" style="display:none" onload="' + __hd + '.onUploadCallback(this,event)"></iframe>');
        _str.push('</form>');
        __convas.id = __key;
        __convas.innerHTML = "";
        __convas.innerHTML = _str.join('');
        __convas.className = "fileupload_convas";
        __convas.style.display = "block";
        __convas.style.position = "absolute";
        __convas.style.left = ((document.documentElement.clientWidth - __convas.offsetWidth) / 2 + document.documentElement.scrollLeft) + "px";
        __convas.style.top = ((document.documentElement.clientHeight - __convas.offsetHeight) / 2 + document.documentElement.scrollTop) + "px";
        __file = $("#f_" + __key);
        __form = $("#fm_" + __key);
        __listBox = $("#l_" + __key);
        __msgObj = $("#m_" + __key);
        _str = null;
    };

    /* BEGIN: ----------------- List ------------*/
    var __imgPattern = ".jpg.png.jpeg.bmp.gif";
    var __parseFileWeight = function (rWeight) {
        var _weight = rWeight;
        if (_weight > 1024 * 1024) {
            _weight = (_weight / (1024 * 1024)) + "";
            _weight = _weight.toFormatFloat(0, 2) + "Mb";
        } else if (_weight > 1024) {
            _weight = (_weight / 1024) + "";
            _weight = _weight.toFormatFloat(0, 2) + "Kb";
        } else {
            _weight += "B";
        }
        return _weight;
    };
    var __showList = function () {
        if (__listData == null || __listData.length == 0) {
            __listBox.innerHTML = "";
            return;
        }
        __listBox.className = "fileupload_list";
        var _str = new Array();
        var eo = null;
        for (var i = 0; i < __listData.length; i++) {
            eo = __listData[i];
            _str.push('<div class="fileupload_l_item">');
            _str.push('<div class="fileupload_l_img" id="' + eo.FileKey + '" onclick="' + __hd + '.onImgItemClick(this,event);">');
            if (__imgPattern.indexOf(eo.ExtName) != -1) {
                _str.push('<span><input type="checkbox" name="cbx_img_list" value="' + eo.FileKey + '" /><a href="' + __viewUrl + eo.FilePath + '" target="_blank">看大图</a></span>');
                _str.push('<img src="' + __viewUrl + eo.Thumbnail + '" onload="jskitUtil.doc.resizeImageOnLoad(this,false);" alt="' + eo.SrcName + eo.ExtName + '(' + __parseFileWeight(eo.FileWeight) + ')" />');
            } else {
                _str.push('<span><input type="checkbox" name="cbx_img_list" value="' + eo.FileKey + '" /><a href="' + __viewUrl + eo.FilePath + '" target="_blank">' + eo.ExtName.toUpperCase() + '</a></span>');
                _str.push('<img src="/cellula_client/default/images/upload_default.png" onload="jskitUtil.doc.resizeImageOnLoad(this,false);" alt="File" />');
            }
            _str.push('</div>');
            if (__showDetails) {
                _str.push('<div class="fileupload_l_info">');
                _str.push(eo.SrcName + eo.ExtName);
                _str.push("(" + __parseFileWeight(eo.FileWeight) + ")");
                if (eo.FileWidth > 0 && eo.FileHeight > 0) {
                    _str.push(" | " + eo.FileWidth + "*" + eo.FileHeight);
                }
                _str.push('</div>');
            }
            _str.push('</div>');
        }
        __listBox.innerHTML = _str.join('');
        __listBox.focus();
        _str = null;
    };
    var __ajax = null;
    var __listTimer = null;
    var __listLoading = false;
    var __listLoadSecond = 0;
    var __listLoadMaxSecond = 30;
    var __loadList = function () {
        __stopListLoad();
        __listLoading = true;
        if (typeof (__listRequest) == "string") {
            __listBox.className = "fileupload_list_loading";
            var url = "Ws/_FileAction.aspx?act=list&model=" + __model + "&model_key=" + __modelKey + "&rm=" + jskitUtil.guid();
            __ajax = new JskitXmlHttpAction(url, __hd + ".__loadListCallback", "text");
            __listTimer = setInterval(__hd + ".__listLoadMonitor", 100);
        }
    };
    this.__listLoadMonitor = function () {
        __listLoadSecond += 0.1;
        if (__listLoadSecond > __listLoadMaxSecond) {
            __stopListLoad();
        }
    };
    var __stopListLoad = function () {
        __listBox.className = "fileupload_list";
        __ajax = null;
        __listLoading = false;
        __listLoadSecond = 0;
    };
    var __stopListDel = function () {
        __ajax = null;
    };
    this.__loadListCallback = function (json) {
        if (__listLoading) {
            try {
                eval("__listData = " + json + ";");
                __showList();
            } catch (e) { alert("List loader:" + e.message); }
        }
        __stopListLoad();
    };
    this.onImgItemClick = function (sender, e) {
        var flg = sender.getAttribute("checked");
        if (flg == "1") {//选中的
            sender.className = "fileupload_l_img";
            sender.setAttribute("checked", "0");
            sender.childNodes[0].childNodes[0].checked = false;
        } else {//未选中
            sender.className = "fileupload_l_img_selected";
            sender.setAttribute("checked", "1");
            sender.childNodes[0].childNodes[0].checked = true;
        }
    };
    var __getSelectItem = function () {
        var cbx = $("@cbx_img_list");
        var keys = new Array();
        if (cbx != null && cbx.length) {
            for (var i = 0; i < cbx.length; i++) {
                if (cbx[i].checked) {
                    keys.push(cbx[i].value);
                }
            }
        }
        cbx = null;
        return keys;
    };
    this.doDelete = function (sender, e) {
        var keys = __getSelectItem();
        if (keys.length > 0 && confirm(unescape("%u786E%u5B9A%u8981%u5220%u9664%uFF1F"))) {
            __stopListDel();
            var url = "Ws/_FileAction.aspx?act=del&model=" + __model + "&model_key=" + __modelKey + "&keys=" + keys.join(',');
            __ajax = new JskitXmlHttpAction(url, __hd + ".delFileCallback", "text");
            __msgObj.innerHTML = unescape("%u6B63%u5728%u6267%u884C%u5220%u9664...");
            url = null;
        } else {
            keys = null;
            __msgObj.innerHTML = unescape("%u8BF7%u9009%u62E9%u8981%u5220%u9664%u7684%u6587%u4EF6");
            return false;
        }
        keys = null;
        return true;
    };
    this.delFileCallback = function (json) {
        __stopListDel();
        __msgObj.innerHTML = unescape("%u5220%u9664%u5B8C%u6210");
        __loadList();
    };
    this.doTop = function (sender, e) {
        var keys = __getSelectItem();
        if (keys.length > 0) {
            __stopListDel();
            var url = "Ws/_FileAction.aspx?act=top&model=" + __model + "&model_key=" + __modelKey + "&key=" + keys[0];
            __ajax = new JskitXmlHttpAction(url, __hd + ".doTopCallback", "text");
            __msgObj.innerHTML = unescape("%u6B63%u5728%u6267%u884C%u524D%u7F6E...");
            url = null;
        } else {
            keys = null;
            __msgObj.innerHTML = unescape("%u8BF7%u9009%u62E9%u8981%u524D%u7F6E%u7684%u6587%u4EF6");
            return false;
        }
        keys = null;
        return true;
    };
    this.doTopCallback = function (bk) {
        __ajax = null;
        if (bk == "") {
            __msgObj.innerHTML = unescape("%u64CD%u4F5C%u5B8C%u6210");
            __loadList();
        } else {
            __msgObj.innerHTML = bk;
        }
    };
    this.doReload = function () {
        __loadList();
    };
    this.doEdit = function () {
        var keys = __getSelectItem();
        if (keys.length > 0) {
            var _str = new Array();
            _str.push('<div>');

            _str.push('</div>');
        }
    };
    /* END:---------------- List ------------*/

    var __stop = function () {
        __sending = false;
        __iframe = null;
        __isFormReady = false;
    };
    var __parseExtName = function (rFileName) {
        return rFileName.substr(rFileName.lastIndexOf("."));
    };
    //打开一个选择文件的窗口    
    this.openFileDialog = function () {
        __file.click();
        __msgObj.innerHTML = "";
    };

    //选定文件后执行上传操作
    this.doUpload = function (sender, e) {
        __stop();
        if (sender.value == "") {
            alert(unescape("%u8BF7%u9009%u62E9%u8981%u4E0A%u4F20%u7684%u6587%u4EF6"));
            return false;
        }
        var _ext = __parseExtName(sender.value);
        if (__invalidFileType(_ext.toLowerCase())) {
            alert(unescape("%u65E0%u6548%u7684%u6587%u4EF6%u683C%u5F0F%uFF0C%u60A8%u53EA%u80FD%u4E0A%u4F20") + __filePattern + unescape("%u683C%u5F0F%u7684%u6587%u4EF6%uFF0C%u8BF7%u91CD%u65B0%u9009%u62E9"));
            return;
        }
        __listBox.focus();
        __form.submit();
        __sending = true;
        __msgObj.innerHTML = unescape("%u6587%u4EF6%u4E0A%u4F20%u4E2D...");
    };
    //检查上传文件的格式是否无效
    var __invalidFileType = function (rExt) {
        if (__filePattern != null) {
            var _fps = __filePattern.split('|');
            var re = null;
            for (var i = 0; i < _fps.length; i++) {
                re = new RegExp(_fps[i], "gi");
                if(re.test(rExt)){return true;}
            }
            return false;
        }
        return false;
    };
    //上传回调函数
    this.onUploadCallback = function (sender, e) {
        if (__sending) {
            __stop();
        }
    };
    //上传失败的回调函数
    this.failed = function (msg) {
        __stop();
        alert(msg);
        __msgObj.innerHTML = unescape("%u4E0A%u4F20%u65F6%u51FA%u73B0%u9519%u8BEF");
    };
    //上传成功的回调函数
    this.succeed = function (eo) {
        __listData.push(eo);
        __showList();
        __stop();
        __msgObj.innerHTML = unescape("%u6210%u529F%u4E0A%u4F20%u4E86%u4E00%u4E2A%u6587%u4EF6%uFF01");
    };
    //关闭文件面板
    this.close = function () {
        __stop();
        __convas.style.display = "none";
        __listBox = null;
        __listData = null;
        __file = null;
        __ajax = null;
        __form = null;
    };
    //设置文件扩展名的过滤
    this.setFilePattern = function (v) {
        __filePattern = (typeof (v) == "string" && v.length > 0) ? v.toLowerCase() : null;
        if (__filePattern != null) {
            __filePattern = __filePattern.replace(/\./gi, "\\.");
            __filePattern = __filePattern.replace(/\*/gi, "[^.]*");
        }
    };
    //设置Form的Action
    this.setAction = function (v) {
        __action = v;
    };
    //设置ModelKey
    this.setModelKey = function (v) {
        __modelKey = v;
    };
    //设置ModelName
    this.setModeName = function (v) {
        __model = v;
    };
    //设置文件列表的ajax请求地址
    this.setListRequest = function (v) {
        __listRequest = v;
    };
    //设置预览的链接根
    this.setViewUrl = function (v) {
        __viewUrl = v;
    }
    //预览
    this.preview = function (rList) {
        __listData = rList;
        __showList();
    };
    //初始化
    this.init = function (rAction, rListRequest, rModel, rModelKey) {
        __action = rAction;
        __listRequest = rListRequest;
        __modelKey = rModelKey;
        __model = rModel;
    };
    //显示面板
    this.display = function (rTitle, rAction, rListRequest) {
        if (typeof (rListRequest) == "string") { __listRequest = rListRequest; }
        if (typeof (rAction) == "string") { __action = rAction; }
        if (typeof (rTitle) == "string") { __title = rTitle; }
        __buildWindow();
        __loadList();
    };
};